<template>
  <div class="org-container">
    <div class="org-toolbar">
      <el-upload
          class="upload-demo"
          action=""
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleImport"
          accept=".xlsx, .xls"
      >
        <el-button type="primary">导入</el-button>
      </el-upload>
      <span class="org-tip">为避免导入组织结构失败，请先
        <el-link type="primary" :underline="false" @click="downloadTemplate">下载模板</el-link>
      </span>
    </div>

    <el-table
        :data="treeData"
        row-key="id"
        :tree-props="{ children: 'children' }"
        border
        style="width: 100%"
        height="420"
    >
      <el-table-column prop="name" label="名称" min-width="300">
        <template #default="scope">
          <div v-if="editingRow && editingRow.id === scope.row.id" class="edit-input">
            <el-input
                v-model="editingName"
                size="small"
                @keyup.enter="saveEdit"
                @keyup.escape="cancelEdit"
                ref="editInput"
            />
          </div>
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="220" />
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <div v-if="editingRow && editingRow.id === scope.row.id" class="edit-actions">
            <el-button type="primary" link @click="saveEdit" size="small">保存</el-button>
            <el-button type="info" link @click="cancelEdit" size="small">取消</el-button>
          </div>
          <div v-else>
            <el-button type="primary" link @click="addChild(scope.row)">新增下级</el-button>
            <el-button type="primary" link @click="editRow(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="removeRow(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="org-pagination">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { utils, writeFileXLSX } from 'xlsx'

// 编辑状态管理
const editingRow = ref(null)
const editingName = ref('')
const editInput = ref(null)

function nowStr() {
  const d = new Date('2021-04-09T14:33:39')
  const yyyy = d.getFullYear()
  const mm = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  const hh = String(d.getHours()).padStart(2, '0')
  const mi = String(d.getMinutes()).padStart(2, '0')
  const ss = String(d.getSeconds()).padStart(2, '0')
  return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`
}

const treeData = ref([
  {
    id: 1,
    name: '河南工业和信息化职业学院',
    createdAt: nowStr(),
    children: [
      {
        id: 101,
        name: '计算机应用技术',
        createdAt: nowStr(),
        children: [
          {
            id: 10101,
            name: '2022级',
            createdAt: nowStr(),
            children: [
              { id: 1010101, name: '1班', createdAt: nowStr() },
              { id: 1010102, name: '2班', createdAt: nowStr() },
              { id: 1010103, name: '3班', createdAt: nowStr() },
            ]
          },
          {
            id: 10102,
            name: '2023级',
            createdAt: nowStr(),
            children: [
              { id: 1010201, name: '1班', createdAt: nowStr() },
              { id: 1010202, name: '2班', createdAt: nowStr() },
              { id: 1010203, name: '3班', createdAt: nowStr() },
            ]
          },
          {
            id: 10103,
            name: '2024级',
            createdAt: nowStr(),
            children: [
              { id: 1010301, name: '1班', createdAt: nowStr() },
              { id: 1010302, name: '2班', createdAt: nowStr() },
              { id: 1010303, name: '3班', createdAt: nowStr() },
            ]
          },
          {
            id: 10104,
            name: '2025级',
            createdAt: nowStr(),
            children: [
              { id: 1010401, name: '1班', createdAt: nowStr() },
              { id: 1010402, name: '2班', createdAt: nowStr() },
              { id: 1010403, name: '3班', createdAt: nowStr() },
            ]
          }
        ]
      }
    ]
  }
])

const total = ref(1)
const currentPage = ref(1)
const pageSize = ref(10)

function onPageChange(page) {
  currentPage.value = page
}
function onPageSizeChange(size) {
  pageSize.value = size
}

function addChild(row) {
  const id = Date.now()
  if (!row.children) row.children = []
  row.children.push({ id, name: '新节点', createdAt: nowStr() })
  ElMessage.success('已新增下级')
}

function editRow(row) {
  editingRow.value = row
  editingName.value = row.name
  nextTick(() => {
    editInput.value?.focus()
  })
}

function saveEdit() {
  if (!editingRow.value) return

  if (editingName.value.trim() === '') {
    ElMessage.warning('名称不能为空')
    return
  }

  editingRow.value.name = editingName.value.trim()
  editingRow.value = null
  editingName.value = ''
  ElMessage.success('已保存')
}

function cancelEdit() {
  editingRow.value = null
  editingName.value = ''
}

function removeRow(row) {
  ElMessageBox.confirm(`确定删除 "${row.name}" 吗？`, '提示', { type: 'warning' })
      .then(() => {
        function dfs(list, id) {
          const idx = list.findIndex(i => i.id === id)
          if (idx !== -1) {
            list.splice(idx, 1)
            return true
          }
          for (const i of list) {
            if (i.children && dfs(i.children, id)) return true
          }
          return false
        }
        dfs(treeData.value, row.id)
        ElMessage.success('已删除')
      })
      .catch(() => {})
}

function handleImport(file) {
  // 处理导入逻辑
  ElMessage.info('导入功能待实现')
}

function downloadTemplate() {
  const ws = utils.aoa_to_sheet([
    ['名称', '上级ID', '创建时间'],
    ['中专部', 11, '2021-04-09 14:33:39']
  ])
  const wb = utils.book_new()
  utils.book_append_sheet(wb, ws, '模板')
  writeFileXLSX(wb, '组织结构模板.xlsx')
}
</script>

<style lang="scss" scoped>
.org-container {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
}

.org-toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.org-tip {
  margin-left: 8px;
  color: #8c8c8c;
}

.edit-input {
  width: 100%;
}

.edit-actions {
  display: flex;
  gap: 8px;
}

.org-pagination {
  display: flex;
  justify-content: center;
  padding: 12px 0 4px 0;
}
</style>
